/**
 * Created by qijialin on 2016/12/29.
 */

var findFlowUrl = serverPath + 'craftProcess/findCraftProcess';
var proDetailUrl = serverPath + 'craftProcess/findCraftProcessDetail';
var proAddUrl = serverPath + 'craftProcess/addCraftProcess';
var proCopyUrl = serverPath + 'craftProcess/copyCraftProcess';
var proDeleteUrl = serverPath + 'craftProcess/delete';
var proEditUrl = serverPath + 'craftProcess/updateCraftProcessDesc';
var proVersionUpUrl = serverPath + 'craftProcess/upgradeCraftProcess';
var proCopyDivIndex = 0;
var proAddDivIndex = 0;
var proFlowEditDivIndex = 0;
var proVersionUpDivIndex = 0;

//版本相关的
var ObjHistoryUrl = serverPath + 'versionHistory/queryVersionHistoryByTypeIdAndObjectId';
var ObjVersionChangeUrl = serverPath + 'versionHistory/queryVersionHistoryById';
var ObjVersionChangeStatusUrl = serverPath + 'versionProcess/queryOptionalState';
var ObjVersionAddVersionHistoryUrl = serverPath + 'versionHistory/addVersionHistory';
var proVersionDetailDivIndex = 0;
var proVersionHistoryDivIndex = 0;
var proVersionChangeDivIndex = 0;

var proTypeId = 4;

//加载时运行
$(function(){
    //根据名称获取Url中某个参数的值
    //var id = GetUrlParam("id");
    //alert("接收id：" + id);

    Init();



    //搜索流程按钮事件
    $('#btnProSearch').click(function () {
        var condition = $('#txtProCondition').val();
        FindData(condition);
    });

    //流程列表数据行 选中 事件 on Check
    $('#proFlowList').on('check.bs.table', function (e, row){
        //拿到行选中的数据
        var proId = row["id"];
        //刷新右边的数据显示
        LoadproDetail(proId);
        LoadproPic(proId);
    });

    //添加 流程 按钮事件
    $('#btnProAdd').click(function () {
        var divUrl = "ProgramAdd.html";
        proAddDivIndex = ibcpLayer.ShowDiv(divUrl, '添加程序', '350px', '400px', function () {
            ListenProAddEvents();
        });
    });

    //拷贝 流程 按钮事件
    $('#btnProCopy').click(function () {
        var divUrl = "ProgramCopy.html";
        proCopyDivIndex = ibcpLayer.ShowDiv(divUrl, '复制程序', '350px', '400px', function () {
            ListenProCopyEvents();
        });
    });

    //删除 流程 按钮事件
    $('#btnProDelete').click(function () {
        var proSel = $('#proFlowList').bootstrapTable('getSelections');
        var delId = proSel[0].id;
        var delMsg = proSel[0].code + '-' + proSel[0].name + '-' + proSel[0].version;

        ibcpLayer.ShowConfirm('您确定要删除程序：' + delMsg, function(){
            ProDeleteEvent(delId)
        });
    });

    //编辑 流程描述 按钮事件  proDescEdit
    $('#btnProDescEdit').click(function () {
            ProDescEditEvent();
    });

    //查看 流程版本详细 按钮事件
    $('#btnProVNow').click(function() {
        var url = "../Version/VersionDetailCheck.html";
        proVersionDetailDivIndex = ibcpLayer.ShowDiv(url, '程序版本详细信息', '400px', '380px', function () {
            $("#VersionDetailTable").bootstrapTable();
            var vsId = $("#proVS").attr('vsId');
            loadVersionDetailData(vsId);
        });
    });

    //查看 流程版本历史 按钮事件
    $('#btnProVHistory').click(function() {
        var url = "../Version/ObjectVersionHistory.html";
        proVersionHistoryDivIndex = ibcpLayer.ShowDiv(url, '程序版本历史信息', '900px', '380px', function() {
            $("#VersionHistoryTable").bootstrapTable();
            var proId = $("#proCode").attr("proId");
            loadDataForObjHistory(proId, proTypeId);
        });

    });

    //变更 流程版本状态 按钮事件
    $('#btnProVChange').click(function() {
        var url = "../Version/ObjectStateChange.html";
        proVersionChangeDivIndex = ibcpLayer.ShowDiv(url, '程序版本变更', '420px', '480px', function () {
            var verId = $("#proVS").attr('vsId');
            LoadVCInfo(verId);
        });
    });

    //升级 流程版本 按钮事件
    $('#btnProVUp').click(function() {
        var url = "ProgramVSUp.html";
        proVersionUpDivIndex = ibcpLayer.ShowDiv(url, '程序版本升级', '350px', '400px', function () {
            $('#PUCode').val($('#proCode').val());
            $('#PUName').val($('#proName').val());
            $('#PUDesc').val($('#proDesc').val());
            ListenProUpEvents();
        });
    });

    //编辑 流程图 按钮事件 proFlowEdit
    $('#btnProFlowEdit').click(function () {
        var proId = $("#proCode").attr('proId');
        var divUrl = "../Editor/WorkFlowEditor/WorkflowEidtor.html?workFlowId=" + proId;
        var iframeWin = null;
        var divIndex = layer.open({
            //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
            // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
            type: 2,
            //动画
            anim: 5,
            //title ：String
            //title: ['文本', 'font-size:18px;']
            //title: false 不显示标题栏
            title: ['编辑程序', 'font-size:18px;font-weight:bold;'],
            //是否固定弹出
            fix: false,
            //最大小化按钮
            maxmin: true,
            //控制点击弹层外区域关闭
            shadeClose: false,
            //窗口大小 area: ['400px', '500px'] or auto 自适应大小
            area: ['1200px', '750px'],
            //area: '350px',
            //iframe层的url
            //content: 'http://www.baidu.com',
            content: divUrl,
            //是否允许拉伸
            resize: false,
            //浏览器滚动条
            scrollbar: false,
            zIndex: layer.zIndex, //重点1
            success: function(layero, index){
                var body = layer.getChildFrame('body', index);
                iframeWin = window[layero.find('iframe')[0]['name']];
            },
            full: function () {
                //iframeWin.Max();
            },
            cancel: function () {
                if(iframeWin.savedCheck()){
                    var sig = iframeWin.initUnloadEvent();        //提示是否需要保存
                    return false;
                    return sig;
                }
            },
            end: function(){}
        });
    });
});

/*****************************************************   初始化   ****************************************************/

//窗口调整大小事件
$(window).resize(function(){
    initPageSize();
});

//初始化
function Init(){
    initPageSize();
    InitBtnStatus();
    InitData();
}

//页面布局初始化
function initPageSize(){
    $('#right2').css('height', $('#leftDiv').height() -  212);
    $('#proFlowEditor').css('height', $('#right2').height() -  50);
    var dataHeight = $('#leftDiv').height() -  100;
    $('#proFlowList').bootstrapTable('refreshOptions',{height:dataHeight});
}

//初始化显示数据
function InitData(){
    var condition = $('#txtProCondition').val();
    FindData(condition);
}

//初始化 按钮状态
function InitBtnStatus(){
    $('#btnProAdd').attr("disabled", false);
    $('#btnProCopy').attr("disabled", true);
    $('#btnProDelete').attr("disabled", true);
    $('#btnProVNow').attr("disabled", true);
    $('#btnProVHistory').attr("disabled", true);
    $('#btnProVChange').attr("disabled", true);
    $('#btnProVUp').attr("disabled", true);
    $('#btnProDescEdit').attr("disabled", true);
    $('#btnProFlowEdit').attr("disabled", true);
}


function ClearProData(){
    $("#proCode").val("");
    $("#proName").val("");
    $("#proVS").val("");
    $("#proStatus").val("");
    $("#proDesc").val("");
    $('#proFlowEditor').attr("src","");
    $("#proDesc").attr("disabled", true);
}


function SetProRowStyle(row, index) {
    if (row.statusName == '失效') {
        return {
            css: {"color": "#7f7f7f"}
        };
    }
    else {
        return {};
    }
}


/*****************************************************   搜索流程   ****************************************************/

//查找数据
function FindData(str){
    InitBtnStatus();
    var datas = {'str':str};
    ibcpAjax.Select(findFlowUrl,datas,true,function(result){
        var data = result.data;
        $('#proFlowList').bootstrapTable('load', data);
        if(data.length >0) {
            //设置选中行
            $('#proFlowList').bootstrapTable('check', 0);
        }
        else {
            ClearProData();
        }

    });
}

function LoadproDetail(proId){
    var datas = {'id':proId};
    ibcpAjax.Select(proDetailUrl,datas,true,function(result) {
        var data = result.data;
        var status = data["statusName"];
        $("#proCode").val(data["code"]);
        $("#proCode").attr('proId', data["id"]);
        $("#proName").val(data["name"]);
        $("#proVS").val(data["version"]);
        $("#proVS").attr('vsId', data["verId"]);
        $("#proStatus").val(status);
        $("#proDesc").val(data["description"]);


        $('#btnProCopy').attr("disabled", false);
        $('#btnProVNow').attr("disabled", false);
        $('#btnProVHistory').attr("disabled", false);
        $('#btnProVChange').attr("disabled", false);
        $('#btnProVUp').attr("disabled", false);

        if(status == "失效"){
            $('#btnProVChange').attr("disabled", true);
        }

        if(status == "编辑"){
            $("#proDesc").attr('readonly',false);
            $('#btnProDescEdit').attr("disabled", false);
            $('#btnProFlowEdit').attr("disabled", false);
            $('#btnProDelete').attr("disabled", false);
            $("#proDesc").attr("disabled", false);
        }
        else {
            $("#proDesc").attr('readonly',true);
            $('#btnProDescEdit').attr("disabled", true);
            $('#btnProFlowEdit').attr("disabled", true);
            $('#btnProDelete').attr("disabled", true);
            $("#proDesc").attr("disabled", true);
        }
    });
}

function LoadproPic(proId){
    var url = '../Editor/WorkFlowEditor/WorkFlowCheck.html?workFlowId=' + proId;
    $('#proFlowEditor').attr("src",url);
}

/*****************************************************   添加 程序   ****************************************************/
//订阅事件
function ListenProAddEvents(){
    $('#btnProAddOK').on('click', function (){
        ProAddOkEvent();
    });

    $('#btnProAddCancel').on('click', function (){
        ProAddCancelEvent();
    });
}

//添加 程序 确认按钮事件
function ProAddOkEvent(){
    //验证
    var paCode = $('#PACode').val();
    var paName = $('#PAName').val();
    var paDesc = $('#PADesc').val();
    var paReason = $('#PAReason').val();
    if(paCode == ''){
        ibcpLayer.ShowTips("请填入代码！",$('#PACode'));
        return;
    }
    if(paName == ''){
        ibcpLayer.ShowTips("请填入名称！",$('#PAName'));
        return;
    }
    if(paReason == ''){
        ibcpLayer.ShowTips("请填入理由！",$('#PAReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'code':paCode,'name':paName,'description':paDesc,'reason':paReason,'sid':sid};
        ibcpAjax.Insert(proAddUrl,datas,true,function(result){
            ibcpLayer.ShowOK('新增成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭新增
            ProAddCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

function ProAddCancelEvent(){
    ibcpLayer.Close(proAddDivIndex);
}

//刷新定位新数据行
function GoToNewRow(newId){
    var sdatas = {'str':$('#txtProCondition').val()};
    ibcpAjax.Select(findFlowUrl,sdatas,true,function(results){
        var data = results.data;
        $('#proFlowList').bootstrapTable('load', data);
        if(data.length >0) {
            //得到新增行数据
            var nowRow = $('#proFlowList').bootstrapTable('getRowByUniqueId',newId);
            //var nowRow = $('#proFlowList').bootstrapTable('getSelections');
            //移除新增行数据
            //$('#proFlowList').bootstrapTable('remove', {field: 'id',values: newId});
            $('#proFlowList').bootstrapTable('removeByUniqueId', newId);

            //将新增的数据放置在第一行
            $('#proFlowList').bootstrapTable("prepend", nowRow);
            //定位新增行
            $("#proFlowList").bootstrapTable("check", 0);
            //$("#proFlowList").bootstrapTable("checkBy", {field:"id", values:[newId]});

        }
    });
}

/*****************************************************   拷贝 程序   ****************************************************/
//订阅事件
function ListenProCopyEvents(){
    $('#btnProCopyOK').on('click', function (){
        ProCopyOkEvent();
    });

    $('#btnProCopyCancel').on('click', function (){
        ProCopyCancelEvent();
    });
}

//拷贝 程序 确认按钮事件
function ProCopyOkEvent(){
    var proSel = $('#proFlowList').bootstrapTable('getSelections');
    var oldId = proSel[0].id;
    //验证
    var pcCode = $('#PCCode').val();
    var pcName = $('#PCName').val();
    var pcDesc = $('#PCDesc').val();
    var pcReason = $('#PCReason').val();
    if(pcCode == ''){
        ibcpLayer.ShowTips("请填入代码！",$('#PCCode'));
        return;
    }
    if(pcName == ''){
        ibcpLayer.ShowTips("请填入名称！",$('#PCName'));
        return;
    }
    if(pcReason == ''){
        ibcpLayer.ShowTips("请填入理由！",$('#PCReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'id':oldId,'code':pcCode,'name':pcName,'description':pcDesc,'reason':pcReason,'sid':sid};
        ibcpAjax.Insert(proCopyUrl,datas,true,function(result){
            ibcpLayer.ShowOK('拷贝成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭拷贝
            ProCopyCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

//拷贝程序取消事件
function ProCopyCancelEvent(){
    ibcpLayer.Close(proCopyDivIndex);
}

/*****************************************************   删除 程序    ****************************************************/

function ProDeleteEvent(delId){
    //签名
    CallSign(100,function(sid){
        var datas = {'id':delId,'sid':sid};
        ibcpAjax.Delete(proDeleteUrl,datas,true,function(){
            SignCancel();
            ibcpLayer.ShowOK('删除成功');
            $('#btnProSearch').trigger('click');
        });
    })
}

/*****************************************************   编辑 程序描述    ****************************************************/

function ProDescEditEvent(){
    var proSel = $('#proFlowList').bootstrapTable('getSelections');
    var oldId = proSel[0].id;
    var proDesc = $('#proDesc').val();

    CallSign(100,function(sid) {
        var datas = {'id': oldId, 'description': proDesc, 'sid': sid};
        ibcpAjax.Update(proEditUrl, datas, true, function () {
            ibcpLayer.ShowOK('保存成功');
            SignCancel();
        });
    });
}

/*****************************************************   查看 程序版本详细    ****************************************************/

// 弹出 版本详细层 获取后台数据
function loadVersionDetailData(id){
    'use strict';
    var datas = {'id': id};

    ibcpAjax.Select(ObjVersionChangeUrl, datas, true, function(result){
        var data = result.data;
        $('#Object_Detail_Version').val(data.version);
        $('#Object_Detail_Version').attr('readonly', 'readonly');
        $('#Object_Detail_State').val(data.toName);
        $('#Object_Detail_State').attr('readonly', 'readonly');
        $('#Object_Detail_StartTime').val(data.validStart);
        $('#Object_Detail_StartTime').attr('readonly', 'readonly');
        $('#Object_Detail_EndTime').val(data.validEnd);
        $('#Object_Detail_EndTime').attr('readonly', 'readonly');
        $('#Object_Detail_Operater').val(data.userName);
    });
}

function VSDetailClose(){
    layer.close(proVersionDetailDivIndex);
}

/*****************************************************   查看 程序版本历史    ****************************************************/
// 弹出层2获取后台数据
function loadDataForObjHistory(objId, typeId){
    'use strict';
    var datas = {'objId': objId, 'typeId': typeId};

    ibcpAjax.Select(ObjHistoryUrl, datas, true, function(result){
        var data = result.data;
        $('#VersionHistoryTable').bootstrapTable('load', data);
    });
}

function VSHistoryClose(){
    layer.close(proVersionHistoryDivIndex);
}
/*****************************************************   变更 程序版本状态    ****************************************************/
//当前版本信息
var objNowVS = '';

//加载当前版本信息
function LoadVCInfo(vId){
    var datas = {'id': vId};
    ibcpAjax.Select(ObjVersionChangeUrl, datas, true, function(result) {
        objNowVS = result.data;
        $('#CurrentVersion').val(objNowVS.version);
        $('#CurrentStatus').val(objNowVS.toName);
        LoadAllowChangeStatusInfo(objNowVS.toStatusId, objNowVS.typeId);
    });
}

//加载可变更状态
function LoadAllowChangeStatusInfo(fromId, typeId){
    var datas = {'fromId': fromId,'typeId': typeId};
    $("#targetStatus").attr('readonly', true);
    $("#ValidDateStart").attr('readonly',true);
    $("#ValidDateEnd").attr('readonly',true);
    $("#ChangeReason").attr('readonly',true);
    $("#btnVCSave").attr('disabled',true);

    ibcpAjax.Select(ObjVersionChangeStatusUrl, datas, true, function(result){
        var data = result.data
        if(data.length > 0){
            $("#targetStatus").attr('readonly', false);
            $("#ValidDateStart").attr('readonly',false);
            $("#ValidDateEnd").attr('readonly',false);
            $("#ChangeReason").attr('readonly',false);
            $("#btnVCSave").attr('disabled',false);

            for(var i=0;i<data.length;i++) {
                var toOptions = "<option value='" + JSON.stringify(data[i]) + "'>" + data[i].toName + "</option>"
                $("#targetStatus").append(toOptions);
                $("#targetStatus").val('');
            }
            //只有一个数据的时候默认选择
            if(data.length == 1){
                $("#targetStatus").prop('selectedIndex', 0);
            }

        }
        else {
            ibcpLayer.ShowMsgCB('没有可变更的状态',function(){VSCCancel();});
        }
    });
}

//版本变更确认按钮事件
function VSCSave(){
    var vStart ='';
    var vEnd ='';
    var status = $("#targetStatus").val();
    var start = $("#ValidDateStart").val();
    var end = $("#ValidDateEnd").val();

    if(status == null || status == ""){
        ibcpLayer.ShowTips('请选择状态',$("#targetStatus"));
        return;
    }

    if(start != null && start != ""){
        vStart = start + ' 00:00:00';
    }

    if(end != null && end != ""){
        vEnd = end + ' 23:59:59';
    }

    if(vEnd != '' && vStart != ''){
        if(vEnd <= vStart){
            ibcpLayer.ShowTips('结束日期 早于 开始日期',$("#ValidDateEnd"));
            return;
        }
    }

    //var selectToInfo = status; //选择的目标状态信息 是字符串 需要转Json
    var selectToInfo = $.parseJSON(status); //选择的目标状态信息 是字符串 需要转Json

    var signNeedId = selectToInfo.aid;   //签名需要的ID
    var toId = selectToInfo.toId;         //目标状态ID
    var reason = $("#ChangeReason").val();

    CallSign(signNeedId,function(sid){
        var datas = {'verFlowId': objNowVS.verFlowId,
            'version': objNowVS.version,
            'fromStatusId': objNowVS.toStatusId,
            'toStatusId': toId,
            'validStart': vStart,
            'validEnd': vEnd,
            'sid': sid,
            'reason': reason,
            'objId': objNowVS.objId,
            'typeId': objNowVS.typeId
        };
        //保存
        ibcpAjax.Insert(ObjVersionAddVersionHistoryUrl,datas,false,function(result){
            SignCancel();
            ibcpLayer.Close(proVersionChangeDivIndex);
            ibcpLayer.ShowOK("操作成功！");
            var proId = $("#proCode").attr('proId');
            GoToNewRow(proId);
            //LoadproDetail(proId);
        });
    });
}

//版本变更取消按钮事件
function VSCCancel(){
    layer.close(proVersionChangeDivIndex);
}
/*****************************************************   升级 程序版本    ****************************************************/
//订阅事件
function ListenProUpEvents(){
    $('#btnProUpOK').on('click', function (){
        ProUpOkEvent();
    });

    $('#btnProUpCancel').on('click', function (){
        ProUpCancelEvent();
    });
}

//添加 程序 确认按钮事件
function ProUpOkEvent(){
    //验证
    var proId = $('#proCode').attr('proId');
    var puReason = $('#PUReason').val();

    if(puReason == ''){
        ibcpLayer.ShowTips("请填入理由！",$('#PUReason'));
        return;
    }
    //签名
    CallSign(100,function(sid){
        var datas = {'id':proId, 'sid':sid, 'reason': puReason};
        ibcpAjax.Insert(proVersionUpUrl,datas,true,function(result){
            ibcpLayer.ShowOK('升级成功');
            var newId = result.data;
            //关闭签名
            SignCancel();
            //关闭新增
            ProUpCancelEvent();
            //刷新定位新数据行
            GoToNewRow(newId);
        });
    })
}

function ProUpCancelEvent(){
    ibcpLayer.Close(proVersionUpDivIndex);
}


/*****************************************************   编辑 程序图    ****************************************************/

function InputRule(value){
    return value.replace(/[^\d]/g,'');
}


//根据名称获取Url中某个参数的值
function GetUrlParam(pname) {
    var reg = new RegExp("(^|&)" + pname + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}